package be.nvlooy.moviereminder.service.implementations;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import be.nvlooy.moviereminder.entities.User;
import be.nvlooy.moviereminder.service.BasicService;
import be.nvlooy.moviereminder.service.UserService;

@Service
@Scope("singleton")
public class UserServiceImpl extends BasicService implements UserService {
	
	private EntityManager em;
	
	@Autowired
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}

	@Override
	public User findByID(int userID) {
		User user = null;
		
		try {
			user = em.find(User.class, (long) userID);
		}
		catch(javax.persistence.NoResultException ex) {}
		
		return user;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findByName(String name) {
		List<User> users = null;
		Query query = em.createNamedQuery("User.getByName");
		query.setParameter("name", "%"+name+"%");
		
		try {
			users = query.getResultList();
		}
		catch(javax.persistence.NoResultException ex) {
			ex.printStackTrace();
		}
	
		return users;
	}
	
	@Override
	public User findByUserName(String username) {
		User user = null;
		Query query = em.createNamedQuery("User.getByUsername");
		query.setParameter("username", username);
		
		try {
			user = (User) query.getSingleResult();
		}
		catch(javax.persistence.NoResultException ex) {}
	
		return user;
	}

	@Override
	public List<User> getUsers() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public User addUser(User user) {
		em.persist(user);
		return user;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public User updateUser(User user) {
		return em.merge(user);
	}

}
